﻿using Emgu.CV;
using Emgu.CV.Structure;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FaceRecognition
{
    public partial class  Form1 :Form
    {
        public Form1 ()
        {
            InitializeComponent();
            image = new Image<Bgr, byte>(320, 240);
            path = "/img";
            label5.ForeColor = Color.Green;
            label10.ForeColor = Color.Green;
            faceImpl = new FaceImpl();
            textBox2.Text += "/"+textBox1.Text;
            comboBox1.SelectedIndex = 0;
            comboBox2.SelectedIndex = 0;
            comboBox3.SelectedIndex = 0;
        }

        VideoCapture cap;
        Image<Bgr, byte> image;
        Image<Bgr, byte> face;
        Image<Bgr, byte>[] eyes ;
        string path;
        FaceImpl faceImpl ;

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                cap = new VideoCapture();
                eyes = new Image<Bgr, byte>[20];
                Application.Idle += ProcessFrame;
                cap.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n" + ex.StackTrace);
            }
        }
        private Image<Bgr, byte> Face(Image<Bgr, byte> img)
        {
            faceImpl.LoadFaceRecognitionFile(comboBox2.Text);
            label5.Text = faceImpl.log;
            return faceImpl.GetFaceImgList(image)[0];
        }
        private List<Image<Bgr, byte>> Eyes(Image<Bgr, byte> face)
        {
            faceImpl.LoadEyeRecognitionFile("haarcascade_eye.xml");
            label5.Text = faceImpl.log;
            return faceImpl.GetEyeImgList(face);
        }
        private void ProcessFrame(object sender, EventArgs e)
        {
            Image<Bgr, byte> img = new Image<Bgr, byte>(cap.Width, cap.Height);
            cap.Retrieve(img, 0);
            image = img.Resize(320, 240, Emgu.CV.CvEnum.Inter.Area);
            pictureBox1.Image = image.Bitmap;
            switch(comboBox1.SelectedIndex)
            {
                case 0:
                    face = Face(image).Resize(200, 200, Emgu.CV.CvEnum.Inter.Area);
                    pictureBox2.Image = face.Bitmap;
                    break;
                case 1:
                    face = Face(image).Resize(200, 200, Emgu.CV.CvEnum.Inter.Area);
                    pictureBox2.Image = face.Bitmap;
                    pictureBox3.Image = Eyes(face)[0].Bitmap;
                    pictureBox4.Image = Eyes(face)[1].Bitmap;
                    break;
            }
            ShowMsg();
            img.Dispose();
        }
        private void ShowMsg()
        {
            label1.Text = "width: "+ cap.Width+"  height: "+cap.Height;
            label5.Text = faceImpl.log;
            label6.Text = "width: " + face.Width + "  height: " + face.Height; 
        }
        private void button1_Click(object sender, EventArgs e)
        {
            string userName = textBox1.Text;
            string filePath = Environment.CurrentDirectory + textBox2.Text;
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath );
            }
            DirectoryInfo dir = new DirectoryInfo(filePath);
            FileInfo[] inf = dir.GetFiles("*.png");
            string last = "";
            int count = inf.Length;
            if(last != "")
                count = Convert.ToInt32( last.Split('_','.')[1])+1;
           
            try
            {
                pictureBox2.Image.Save(filePath +  "/" + userName + "_" + count + ".png");
                label7.ForeColor = Color.Green;
                label7.Text = userName + "_" + count+".png"+" 保存成功";
            }
            catch
            {
                label7.ForeColor = Color.Red;
                label7.Text = "图像为空";
            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            
            textBox2.Text = path + "/" + textBox1.Text;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if(cap != null)
            if(button3.Text == "暂停")
            {
                Application.Idle -= ProcessFrame;
                button3.Text = "继续";
                label5.Text = "暂停检测";
                }
            else
            {
                Application.Idle += ProcessFrame;
                button3.Text = "暂停";
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (cap != null)
                if (button4.Text == "暂停")
                {
                    Application.Idle -= ProcessFrame;
                    button4.Text = "继续";
                    label5.Text = "暂停检测";
                }
                else
                {
                    Application.Idle += ProcessFrame;
                    button4.Text = "暂停";
                }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            string filePath = Environment.CurrentDirectory + textBox3.Text;
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            DirectoryInfo dir = new DirectoryInfo(filePath);
            FileInfo[] inf = dir.GetFiles("*.png");
            string last = "";
            int count = inf.Length;
            if (last != "")
                count = Convert.ToInt32(last.Split('_', '.')[1]) + 1;
            try
            {
                pictureBox2.Image.Save(filePath + "/" + "cap_" + count + ".png");
                label10.ForeColor = Color.Green;
                label10.Text = " 保存成功";
            }
            catch
            {
                label10.ForeColor = Color.Red;
                label10.Text = "图像为空";
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            string srcpath = textBox4.Text;
            string despath = textBox5.Text;
            if(!Directory.Exists(srcpath))
            {
                MessageBox.Show("文件夹不存在的");
                return;
            }
            if (!Directory.Exists(despath))
            {
                Directory.CreateDirectory(despath);
            }
            DirectoryInfo dir = new DirectoryInfo(srcpath);
            FileInfo[] inf = dir.GetFiles("*.pgm");
            progressBar1.Maximum = inf.Length;
            int count = 0;
            progressBar1.Visible = true;
            progressBar1.Value = 0;
            foreach (FileInfo f in inf )
            {
                try
                {
                    string savepath = despath + "\\"+ f.Name.Replace(f.Extension, "") + comboBox3.Text;
                    PgmToPng.GetPng(PgmToPng.GetPgmFileGrayArray(f.FullName)).Save(savepath);
                
                    count++;
                    progressBar1.Value++;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("转换失败，详细原因:\n" + ex.Message + "\n" + ex.StackTrace);
                }
                label11.ForeColor = Color.Green;
                label11.Text = "转换 "+count + "/"+inf.Length+" 个";
            }
            
        }

        private void button7_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog()==DialogResult.OK)
            {
                image = new Image<Bgr, byte>(ofd.FileName);
                switch (comboBox1.SelectedIndex)
                {
                    case 0:
                        pictureBox1.Image = image.Bitmap;
                        face = Face(image).Resize(200, 200, Emgu.CV.CvEnum.Inter.Area);
                        pictureBox2.Image = face.Bitmap;
                        break;
                    case 1:
                        pictureBox1.Image = image.Bitmap;
                        face = Face(image).Resize(200, 200, Emgu.CV.CvEnum.Inter.Area);
                        pictureBox2.Image = face.Bitmap;
                        pictureBox3.Image = Eyes(face)[0].Bitmap;
                        pictureBox4.Image = Eyes(face)[1].Bitmap;
                        break;
                }
                //ShowMsg();
            }
        }
    }
}
